package com.qianheng.kit.base.java.thread.pool;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.ehcache.core.util.CollectionUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@Slf4j
public class MyThreadPool {
    public static final ThreadPoolExecutor THREAD_POOL_EXECUTOR;
    static {
        THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
                //核心线程数等，都能动态修改。
                10,10,100, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(15),
                new ThreadFactoryBuilder().setNamePrefix("qh_pool").build(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        THREAD_POOL_EXECUTOR.allowCoreThreadTimeOut(true);
        Runtime.getRuntime().addShutdownHook(new Thread(()->THREAD_POOL_EXECUTOR.shutdown()));
    }

    public static void main(String[] args) {
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        for (int i = 0; i < 1000; i++) {
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                log.info(Thread.currentThread().getName());
            }, THREAD_POOL_EXECUTOR);
            futures.add(voidCompletableFuture);
        }

        //等待所有future
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        log.info("执行完成");

        THREAD_POOL_EXECUTOR.shutdown();

    }


}
